from flask import render_template, request, redirect, url_for

from . import book_bp
from models.books import Author, Book
from models import db


@book_bp.route('/')
def index():
    return {'msg': 'books蓝图首页'}


@book_bp.route('/manage', methods=['GET', 'POST'])
def manage():
    """书籍管理界面"""
    # 查询所有的作者信息
    if request.method == 'POST':
        formdict = request.form
        if formdict['author'] != '' and formdict['book'] != '':
            # todo:相同作者无法保存
            author = Author(name=formdict['author'])
            db.session.add(author)
            db.session.commit()
            book = Book(name=formdict['book'], author_id=author.id)
            db.session.add(book)
            db.session.commit()
        return redirect(url_for('books.manage'))
    authors = Author.query.all()
    context = {
        'authors': authors
    }
    return render_template('book_manager.html', **context)


@book_bp.route('/add_book')
def add_book():
    """添加一些书籍与作者的信息"""
    try:
        au1 = Author(name='老王')
        au2 = Author(name='老张')
        au3 = Author(name='老刘')
        # 把数据提交给用户会话
        db.session.add_all([au1, au2, au3])
        # 提交会话
        db.session.commit()
        bk1 = Book(name='老王回忆录', author_id=au1.id)
        bk2 = Book(name='我读书少，你别骗我', author_id=au1.id)
        bk3 = Book(name='如何才能让自己更骚', author_id=au2.id)
        bk4 = Book(name='怎样征服美丽少女', author_id=au3.id)
        bk5 = Book(name='如何征服英俊少男', author_id=au3.id)
        # 把数据提交给用户会话
        db.session.add_all([bk1, bk2, bk3, bk4, bk5])
        # 提交会话
        db.session.commit()
        return {'msg': '添加成功'}
    except Exception as e:
        return {'msg': '添加失败'}


@book_bp.route('/feedback')
def feedback():
    return render_template('others/12.9.html')
